#include "driver_i2c.h"


void I2C_Delay(uint32_t tick)
{  
    volatile uint32_t tmp = tick;
    while(tmp--);
}


void I2C_GPIO_ReInit(void)
{
     GPIO_InitTypeDef GPIO_InitStruct = {0};
     __HAL_RCC_GPIOA_CLK_ENABLE();
     
     GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD;
     GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
     
     GPIO_InitStruct.Pin = SCL_Pin;
     HAL_GPIO_Init(SCL_GPIO_Port, &GPIO_InitStruct);
     
     GPIO_InitStruct.Pin = SDA_Pin;
     HAL_GPIO_Init(SDA_GPIO_Port, &GPIO_InitStruct); 
}


void I2C_Start(void)
{
    SCL_H;
    SDA_H;
    I2C_Delay(100);
    SDA_L;
    I2C_Delay(100);  
    SCL_L;
}


void I2C_Stop(void)
{
    SCL_H;       
    SDA_L;
    I2C_Delay(100);
    SDA_H;
    I2C_Delay(100);
}


/* 主机接收一个应答信号 */
uint8_t I2C_GetAck_From_Slave(void)
{
    uint8_t ack;
    SCL_L;
    I2C_Delay(100);
    SCL_H;
    I2C_Delay(100);
    if(SDA_RD == 1)
    {
        ack = 1;
    }else{
        ack = 0;
    }        
    SCL_L;
    I2C_Delay(100);
    return ack;
}


/* 主机发送一个应答信号 */
void I2C_Master_Ack(uint8_t ack)
{
    SCL_L;
    SDA_L;
    if(ack)
    {        
        SDA_H;
    }else
    {
        SDA_L;
    }
    I2C_Delay(100);
    SCL_H;
    I2C_Delay(100);
    SCL_L;
    I2C_Delay(100);
}


void I2C_WriteByte(uint8_t data)
{
    int i;
    SCL_L;
    SDA_L;    
    for(i=0;i<8;i++)
    {
        if(data & 1<<(7-i))
        {
            SDA_H;
        }else{
            SDA_L;
        }
        I2C_Delay(100);
        SCL_H;
        I2C_Delay(100);
        SCL_L;
        I2C_Delay(100);
    }   
}
  

uint8_t I2C_ReadByte(void)
{
    uint8_t data = 0;
    int i;
    SCL_L;
    I2C_Delay(100);
    for(i=0;i<8;i++)
    {
        SCL_H;
        I2C_Delay(100);
        if(SDA_RD == 1)
        {
            data |= 1<<(7-i);
        }
        SCL_L;
        I2C_Delay(100);
    }
    return data;
}

